const fs = require('fs')
const path = require('path')
const marked = require('marked')
const yaml = require('js-yaml')

const SUFFIX = '.md'
const REMOVE_BACKUP = true

FRONTMATTERS = [
  // required
  'title',
  'description',
  'position',

  // positional
  'category',
  'version',
  'fullScreen',
  'menuTitle',
]

const ROOT = path.resolve(__dirname, '../content')

const getDirName = (filePath) =>
  filePath.match(/(?<=\\?)([^\\]*?)\\[^\\]*?\.md$/)[1]

const getFileName = (filePath) => filePath.match(/([^\\/]*?)(?:\.\w*)?$/)[1]

function queryAllFiles(pathBase = '', paths = []) {
  fs.readdirSync(path.join(ROOT, pathBase), { withFileTypes: true }).forEach(
    (dirent) => {
      const m = dirent.name.match(/^[APSG]\d+-/)
      if (m) {
        const newName = dirent.name.replace(m[0], '')
        fs.renameSync(
          path.join(ROOT, pathBase, dirent.name),
          path.join(ROOT, pathBase, newName)
        )
        dirent.name = newName
      }
      const direntPath = path.join(pathBase, dirent.name)
      if (dirent.isDirectory()) {
        queryAllFiles(direntPath, paths)
      } else if (dirent.name.endsWith(SUFFIX)) {
        paths.push(direntPath)
      } else if (dirent.name.endsWith('_') && REMOVE_BACKUP) {
        fs.unlink(path.join(ROOT, pathBase, dirent.name), (err) => {
          if (err) throw err
          console.log('removed backup file: ', dirent.name)
        })
      }
    }
  )
  return paths
}

function onUpdateFrontMatter(text, filePathBase) {
  const m = text.match(/^---\r?\n(.*?)^---/ms)
  if (!m) {
    throw filePathBase
  }
  const s = m[1]
  const j = yaml.safeLoad(s) || {}

  j.title = (j.title || getFileName(filePathBase))
    .split('_')
    .map((s) => s[0].toUpperCase() + s.substring(1))
    .join(' ')
  j.menuTitle = getFileName(filePathBase)
  j.description = j.description || j.desc || j.title

  j.relativePath = filePathBase.replace(/\\/g, '/')
  j.slug = j.slug || j.permalink || escape(j.title.replace(' ', '-'))

  j.tags = j.tags || [getDirName(filePathBase)]
  j.category = j.tags[0]

  j.cover = j.cover && j.cover.startsWith('http') ? j.cover : ''
  j.date = j.date || ''

  j.position = 100
  j.version = '0.1.0'
  j.fullScreen = false

  delete j.desc
  delete j.permalink

  const y = yaml.dump(j)

  const textNew = text.replace(s, y)

  console.log({ s, y })

  return textNew
}

function onDeleteHeader1(text) {
  const t = /^#\s.*?$/gm
  if (t.test(text)) {
    console.log('matched t')
    return text.replace(t, '')
  }
  return text
}

function onUpdateTip(text) {
  return text.replace(/(?<=<\/?)alert(?=>)/gms, 'tip')
}

function onElevateIndexFile(filePathBase) {
  if (filePathBase.endsWith('about.md')) {
    fs.renameSync(
      path.join(ROOT, filePathBase),
      path.join(ROOT, filePathBase.replace(/[\\/]index/, ''))
    )
    console.log('renamed: ', filePathBase)
    fs.rmdirSync(path.join(ROOT, filePathBase.replace('about.md', '')), {
      recursive: true,
    })
    console.log('deleted: ', getDirName(filePathBase))
  }
}

const readAndWrite = (
  filePathBase,
  updateFunction,
  writeNew = true,
  backup = true
) =>
  fs.readFile(path.join(ROOT, filePathBase), 'utf-8', (err, text) => {
    if (err) throw err
    const textNew = updateFunction(text, filePathBase)
    if (!textNew) throw new Error('返回内容不得为空')
    if (backup && !REMOVE_BACKUP) {
      fs.writeFileSync(path.join(ROOT, filePathBase + '_'), text)
      console.log('backup content to: ', filePathBase + '_')
    }

    if (writeNew) {
      fs.writeFileSync(path.join(ROOT, filePathBase.replace(/_$/, '')), textNew)
      console.log('write new content to: ', filePathBase.replace(/_$/, ''))
    }
    return textNew
  })

const pathList = queryAllFiles('zh')
pathList.map((filePathBase) => readAndWrite(filePathBase, onUpdateTip))
